#include"Stack.h"

// 初始化
void STInit(ST* ps)
{
	assert(ps);
	ps->a = NULL;
	ps->capacity = ps->size = 0;
}

// 销毁
void STDestroy(ST* ps)
{
	assert(ps);
	free(ps->a);
	ps->a = NULL;
	ps->capacity = ps->size = 0;
}

// 入栈
void STPush(ST* ps, STDataType x)
{
	assert(ps);
	// 是否要扩容
	if (ps->capacity == ps->size)
	{
		int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		STDataType* temp = (STDataType*)malloc(sizeof(STDataType) * newcapacity);
		if (temp == NULL)
		{
			perror("malloc fail");
			return;
		}
		ps->a = temp;
		ps->capacity = newcapacity;
	}
	ps->a[ps->size] = x;
	ps->size++;
}

// 出栈
void STPop(ST* ps)
{
	assert(ps);
	assert(!STEmpty(ps));
	// 栈顶元素出栈
	ps->size--;
}

// 获取栈顶元素
STDataType STTop(ST* ps)
{
	assert(ps);
	assert(!STEmpty(ps));
	return ps->a[ps->size - 1];
}

int STSize(ST* ps)
{
	assert(ps);
	return ps->size;
}

bool STEmpty(ST* ps)
{
	assert(ps);
	return ps->size == 0;
}